package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.archiveUnit.ArchiveUnitModifyRequest;
import com.ktwlsoft.archivemanage.payload.inforConst.InfrastructureModifyRequest;
import com.ktwlsoft.archivemanage.payload.basic.ResetPasswordRequest;
import com.ktwlsoft.archivemanage.payload.unitMember.UnitMemberModifyRequest;
import com.ktwlsoft.archivemanage.service.utils.PassWordUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import com.ktwlsoft.archivemanage.service.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 我的
 *
 * @author zhuhe on 2019/10/24 17:03
 * @version 1.0
 */
@Component
public class MyInformationService {

    /**立档单位*/
    private final ArchiveUnitRepositoryService archiveUnitService;

    /**单位人员*/
    private final UnitMemberRepositoryService unitMemberService;

    /**基础设施*/
    private final InfrastructureRepositoryService infrastructureService;

    private final PasswordEncoder passwordEncoder;

    private final AuthenticationManager authenticationManager;

    private final AccountRepositoryService accountRepositoryService;

    private final ImgsService imgsService;

    public MyInformationService(ArchiveUnitRepositoryService archiveUnitService, UnitMemberRepositoryService unitMemberService, InfrastructureRepositoryService infrastructureService, PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, AccountRepositoryService accountRepositoryService, ImgsService imgsService) {
        this.archiveUnitService = archiveUnitService;
        this.unitMemberService = unitMemberService;
        this.infrastructureService = infrastructureService;
        this.passwordEncoder = passwordEncoder;
        this.authenticationManager = authenticationManager;
        this.accountRepositoryService = accountRepositoryService;
        this.imgsService = imgsService;
    }

    /**
      * 我的详情 on 2019/10/24 17:06
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> myInformationDetail(Long id){
        JSONObject object = new JSONObject();
        ArchiveUnit archiveUnit = archiveUnitService.getById(id);
        UnitMember unitMember = null;
        Infrastructure infrastructure = null;
        JSONObject unitMemberjson = new JSONObject();
        if(archiveUnit != null && archiveUnit.getId() != null) {
            //立档单位
            JSONObject archiveUnitjson = JSONObject.parseObject(JSON.toJSONString(archiveUnit, SerializerFeature.WriteMapNullValue));
            //单位图片
            Imgs imgs = new Imgs();
            imgs.setBusinessId(archiveUnit.getId());
            imgs.setBusinessType("unitFile");
            archiveUnitjson.put("unitFile",imgsService.getByBusinessIdAndBusinessType(imgs));
            object.put("archiveUnit",archiveUnitjson);
            //证件图片
            Imgs imgs1 = new Imgs();
            imgs1.setBusinessId(archiveUnit.getId());
            imgs1.setBusinessType("certificateFile");
            archiveUnitjson.put("certificateFile",imgsService.getByBusinessIdAndBusinessType(imgs1));
            object.put("certificateFile",archiveUnitjson);
            //单位人员
            unitMember = unitMemberService.getByUnitId(archiveUnit.getId());
            unitMemberjson = JSONObject.parseObject(JSON.toJSONString(unitMember, SerializerFeature.WriteMapNullValue));
            Imgs memberFile = new Imgs();
            memberFile.setBusinessId(archiveUnit.getId());
            memberFile.setBusinessType("memberFile");
            unitMemberjson.put("memberFile",imgsService.getByBusinessIdAndBusinessType(memberFile));
            //基础设施
            infrastructure = infrastructureService.getByUnitId(archiveUnit.getId());
        }
        object.put("UnitMember",unitMemberjson);
        object.put("Infrastructure",infrastructure);
        return Result.ok(object);
    }

    /**
      * 重置密码 on 2019/10/24 17:54
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> resetPassword(ResetPasswordRequest request){
        ArchiveUnit archiveUnit = archiveUnitService.getByAccount(request.getAccount());
        if(archiveUnit == null){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("该用户不存在");
        }
        if(!passwordEncoder.matches(request.getOidPassword(),archiveUnit.getPassword())){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("旧密码输入不正确");
        }
        if(!request.getNewPassword().equals(request.getRepeatNewPassword())){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("重复新密码输入不正确");
        }
        if(!PassWordUtils.checkPasswordIsStrong(request.getNewPassword())){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("密码不能为空并且密码长度不小于8位数,包含小写字母,大写字母,数字和特殊字符");
        }
        archiveUnit.setPassword(passwordEncoder.encode(request.getNewPassword()));
        Account account = accountRepositoryService.getById(archiveUnit.getAccountId());
        try {
            archiveUnitService.update(archiveUnit);
            if(account != null){
                account.setPassword(passwordEncoder.encode(request.getNewPassword()));
                account.setPasswordStrength(UserUtils.testingPasswordStrength(request.getNewPassword()));
                accountRepositoryService.update(account);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request, ResultType.UPDATE_ERROR);
        }
        return Result.body(null,ResultType.BUSINESS_SUCCESS);
    }

    /**
      * 单位情况修改 on 2019/10/25 9:14
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> archiveUnitModify(ArchiveUnitModifyRequest request){
        ArchiveUnit archiveUnit = new ArchiveUnit();
        BeanUtils.copyProperties(request,archiveUnit);
        archiveUnit.setCreatedAt(null);
        archiveUnit.setCreator(null);
        archiveUnit.setCreatorId(null);
        //证件上传
        if(request.getIdentityFile() != null && request.getIdentityFile().size() > 0){
            //删除
            ImgUploadService.deleteByBIdAndBType(archiveUnit.getId(),"certificateFile");
            ImgUploadService.imgUploads(request.getIdentityFile(), String.valueOf(archiveUnit.getId()), "certificateFile");
        }
        //图片上传
        if(request.getUnitImgFile() != null) {
            //删除
            ImgUploadService.deleteByBIdAndBType(request.getId(),"unitFile");
            //上传
            List<MultipartFile> multipartFiles = Lists.newArrayList();
            multipartFiles.add(request.getUnitImgFile());
            List<Imgs> imgss = ImgUploadService.imgUploads(multipartFiles, String.valueOf(archiveUnit.getId()), "unitFile");
            if (imgss != null && imgss.size() > 0) {
                archiveUnit.setUnitImg(String.valueOf(imgss.get(0).getId()));
            }
        }
        //证件url新增图片
        if(request.getIdentityFileUrl() != null && request.getIdentityFileUrl().size() > 0){
            //删除
            ImgUploadService.deleteByBIdAndBType(archiveUnit.getId(),"certificateFile");
            imgSave(request.getIdentityFileUrl(),archiveUnit.getId(),"certificateFile");
        }
        //单位图片url上传
        if(request.getUnitImgFileUrl() != null) {
            //删除
            ImgUploadService.deleteByBIdAndBType(request.getId(),"unitFile");
            //上传
            List<String> strings = Lists.newArrayList();
            strings.add(request.getUnitImgFileUrl());
            Long aLong = imgSave(strings,archiveUnit.getId(),"unitFile");
            if (aLong != null && aLong != 0) {
                archiveUnit.setUnitImg(String.valueOf(aLong));
            }
        }
        try {
            archiveUnitService.update(archiveUnit);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request, ResultType.UPDATE_ERROR);
        }
        return Result.ok(request);
    }

    /**
      * 人员信息修改 on 2019/10/25 9:42
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> unitMemberModify(UnitMemberModifyRequest request){
        UnitMember unitMember = new UnitMember();
        BeanUtils.copyProperties(request,unitMember);
        unitMember.setCreator(null);
        unitMember.setCreatorId(null);
        unitMember.setCreatedAt(null);
        //图片上传
        if(request.getProfileFile() != null) {
            //删除
            ImgUploadService.deleteByBIdAndBType(unitMember.getUnitId(),"memberFile");
            List<MultipartFile> multipartFiles = Lists.newArrayList();
            multipartFiles.add(request.getProfileFile());
            List<Imgs> imgss = ImgUploadService.imgUploads(multipartFiles, String.valueOf(unitMember.getUnitId()), "memberFile");
            if (imgss != null && imgss.size() > 0) {
                unitMember.setProfile(String.valueOf(imgss.get(0).getId()));
            }
        }
        //图片url上传
        if(request.getProfileFileUrl() != null) {
            //删除
            ImgUploadService.deleteByBIdAndBType(unitMember.getUnitId(),"memberFile");
            List<String> strings = Lists.newArrayList();
            strings.add(request.getProfileFileUrl());
            Long aLong = imgSave(strings,unitMember.getUnitId(),"memberFile");
            if (aLong != null && aLong != 0) {
                unitMember.setProfile(String.valueOf(aLong));
            }
        }
        Account account = accountRepositoryService.getById(unitMember.getRecorderId());
        Account checkUnique = new Account();
        checkUnique.setTeleNum(request.getRecorderTele());
        checkUnique.setRoleName("立档单位");
        List<Account> accounts = accountRepositoryService.checkUnique(checkUnique);
        if(accounts != null && accounts.size() > 1){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("该手机号存在复数账号");
        }
        if(accounts != null && accounts.size() > 0 && !accounts.get(0).getId().equals(account.getId())){
            return Result.body(request, ResultType.CHECK_ERROR).withMessage("档案员手机号重复");
        }
        try {
            if(account != null){
                account.setProfile(unitMember.getProfile());
                account.setTeleNum(unitMember.getRecorderTele());
                account.setRealName(unitMember.getRecorder());
                accountRepositoryService.update(account);
            }
            unitMemberService.updateByPrimaryKeySelective(unitMember);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request, ResultType.UPDATE_ERROR);
        }
        return Result.ok(request);
    }

    /**
      * 基础设施修改 on 2019/10/25 10:02
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> infrastructureModify(InfrastructureModifyRequest request){
        Infrastructure infrastructure = new Infrastructure();
        BeanUtils.copyProperties(request,infrastructure);
        infrastructure.setCreatedAt(null);
        infrastructure.setCreator(null);
        infrastructure.setCreatorId(null);
        try {
            infrastructureService.updateByPrimaryKeySelective(infrastructure);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request, ResultType.UPDATE_ERROR);
        }
        return Result.ok(request);
    }

    /**
      * 新增证件图片 on 2019/11/11 9:46
      *
      * @param list list
      * @param businessId businessId
      * @param businessType businessType
      * @return int int
      */
    private Long imgSave(List<String> list,Long businessId,String businessType){
        Long id = null;
        for(String s:list) {
            // 新增数据到数据库
            Imgs imgs = new Imgs();
            //id
            imgs.setId(SnowFlake.getNextId());
            //业务id
            imgs.setBusinessId(businessId);
            //业务类型
            imgs.setBusinessType(businessType);
            //相对地址
            imgs.setUrl(s);
            //名称
            String fileName = s.substring(s.lastIndexOf(File.separator)+1,s.length());
            imgs.setFileName(fileName);
            //后缀
            String[] strings = fileName.length() > 0?fileName.split("\\."):null;
            imgs.setSuffix(strings != null?strings[strings.length - 1]:"");
            //大小
            imgs.setSize(0L);
            //创建人
            imgs.setCreator(null);
            //创建人id
            imgs.setCreatorId(null);
            //创建时间
            imgs.setCreatedAt(new Date());
            //更新时间
            imgs.setUpdateAt(new Date());
            try {
                imgsService.insert(imgs);
            } catch (Exception e) {
                e.printStackTrace();
                return 0L;
            }
            id = imgs.getId();
        }
        return id;
    }
}